package com.kye.express.business.jd.goods_list_by_category;

import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;

import com.beloo.widget.chipslayoutmanager.ChipsLayoutManager;
import com.jakewharton.rxbinding2.view.RxView;
import com.kye.base.DebounceObservableTransformer;
import com.kye.base.Logger;
import com.kye.base.utils.GsonUtils;
import com.kye.express.R;
import com.kye.express.business.base.BaseToolbarActivity;
import com.kye.express.business.jd.goods_detail.JDGoodsDetailActivity;
import com.kye.express.business.jd.goods_list_by_category.model.JDCategorySelectModel;
import com.kye.express.business.jd.goods_list_by_category.model.JDCategoryTagModel;
import com.kye.express.business.jd.goods_list_by_category.model.JDIntegralSelectModel;
import com.kye.express.business.jd.goods_list_by_category.viewbinder.JDCategorySelectViewBinder;
import com.kye.express.business.jd.goods_list_by_category.viewbinder.JDCategoryTagsViewBinder;
import com.kye.express.business.jd.goods_list_by_category.viewbinder.JDGoodsListItemViewBinder;
import com.kye.express.business.jd.goods_list_by_category.viewbinder.JDIntegralSelectViewBinder;
import com.kye.express.databinding.ActivityJdgoodsListByCategoryBinding;
import com.kye.express.utils.ToolbarManager;
import com.kye.express.view.ToastManager;
import com.kye.express.view.reclyerview.GridSpacingItemDecoration;
import com.kye.lib.view.statuslayout.StatusLayout;
import com.kye.model.base.Data3ResultSet;
import com.kye.model.base.PageInfo;
import com.kye.model.bean.jd.shop.JDGoodsCategoryBean;
import com.kye.model.bean.jd.shop.JDGoodsItemBean;
import com.kye.model.bean.jd.shop.JDGoodsListResultBean;
import com.kye.model.bean.user.User;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Single;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import me.drakeet.multitype.MultiTypeAdapter;

public class JDGoodsListByCategoryActivity extends BaseToolbarActivity implements JDGoodsListByCategoryConstract.JDGoodsListByCategoryView, JDCategorySelectViewBinder.OnCategoryItemListener, JDIntegralSelectViewBinder.OnIntegralItemListener, JDCategoryTagsViewBinder.OnTagsItemListener, JDGoodsListItemViewBinder.OnGoodsItemListener {

    private final static String TAG_EXCHANGE_RATE = "TAG_EXCHANGE_RATE";
    private ActivityJdgoodsListByCategoryBinding binding;
    private JDGoodsListByCategoryConstract.JDGoodsListByCategoryPresenter presenter;
    private JDGoodsCategoryBean categoryBean;
    private User userInfo;
    private double exchangeRate;

    private MultiTypeAdapter categoryListAdapter;
    private MultiTypeAdapter integralListAdapter;
    private MultiTypeAdapter categoryTagsAdapter;
    private MultiTypeAdapter goodsAdapter;

    private JDCategorySelectModel selectedCategoryModel;
    private JDCategoryTagModel selectedTagModel;
    private JDIntegralSelectModel selectIntegralModel;

    public static void startActivity(Context context, JDGoodsCategoryBean categoryBean, double exchangeRate) {
        Intent intent = new Intent(context, JDGoodsListByCategoryActivity.class);
        intent.putExtra(JDGoodsCategoryBean.class.getName(), categoryBean);
        intent.putExtra(TAG_EXCHANGE_RATE, exchangeRate);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState == null) {
            categoryBean = getIntent().getParcelableExtra(JDGoodsCategoryBean.class.getName());
            exchangeRate = getIntent().getDoubleExtra(TAG_EXCHANGE_RATE,1);
        } else {
            categoryBean = savedInstanceState.getParcelable(JDGoodsCategoryBean.class.getName());
            exchangeRate = savedInstanceState.getDouble(TAG_EXCHANGE_RATE);
        }
        binding = DataBindingUtil.setContentView(this, R.layout.activity_jdgoods_list_by_category);
        presenter = new JDGoodsListByCategoryConstract.JDGoodsListByCategoryPresenter();
        initToolbar(savedInstanceState);
        initViews(savedInstanceState);
        initEvents(savedInstanceState);
        initData(savedInstanceState);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putParcelable(JDGoodsCategoryBean.class.getName(), categoryBean);
        outState.putDouble(TAG_EXCHANGE_RATE, exchangeRate);
        super.onSaveInstanceState(outState);
    }

    private void initToolbar(Bundle savedInstanceState) {
        ToolbarManager.setToolbar(this, binding.toolbar);
        binding.toolbar.setTitleTextColor(getResources().getColor(R.color.white));
    }

    private void initViews(Bundle savedInstanceState) {

//        binding.toolbar.setTitle(categoryBean.getClassName());
        getSupportActionBar().setTitle(categoryBean.getClassName());

        /**
         * 类别item
         */
        categoryListAdapter = new MultiTypeAdapter();
        categoryListAdapter.register(JDCategorySelectModel.class, new JDCategorySelectViewBinder(this));
        binding.categoryList.setLayoutManager(new LinearLayoutManager(this));
        binding.categoryList.setAdapter(categoryListAdapter);

        /**
         * 积分item
         */
        integralListAdapter = new MultiTypeAdapter();
        integralListAdapter.register(JDIntegralSelectModel.class, new JDIntegralSelectViewBinder(this));
        binding.integralList.setLayoutManager(new LinearLayoutManager(this));
        binding.integralList.setAdapter(integralListAdapter);

        /**
         * 类别tag
         */
        categoryTagsAdapter = new MultiTypeAdapter();
        ChipsLayoutManager spanLayoutManagerHot = ChipsLayoutManager.newBuilder(this)
                .setOrientation(ChipsLayoutManager.HORIZONTAL)
                .build();
        binding.categoryTags.setLayoutManager(spanLayoutManagerHot);
        binding.categoryTags.setAdapter(categoryTagsAdapter);
        categoryTagsAdapter.register(JDCategoryTagModel.class, new JDCategoryTagsViewBinder(this));

        /**
         * 商品list
         */
        goodsAdapter = new MultiTypeAdapter();
        goodsAdapter.register(JDGoodsItemBean.class, new JDGoodsListItemViewBinder(this));
        binding.goodsList.setLayoutManager(new GridLayoutManager(this, 2));
        binding.goodsList.addItemDecoration(new GridSpacingItemDecoration(2, 5, false));
        binding.goodsList.setItemAnimator(new DefaultItemAnimator());
        binding.goodsList.setAdapter(goodsAdapter);
    }

    private void initEvents(Bundle savedInstanceState) {
        // 全局界面
        RxView.clicks(binding.llErrorServer.btErrorServerRetry)
                .compose(this.bindToLifecycleDestroy())
                .compose(new DebounceObservableTransformer<Object>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        binding.statusLayout.showLoadingView();
                    }
                });
        RxView.clicks(binding.llErrorNet.btErrorNetRetry)
                .compose(this.bindToLifecycleDestroy())
                .compose(new DebounceObservableTransformer<Object>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        binding.statusLayout.showLoadingView();
                    }
                });
        RxView.clicks(binding.llEmpty.btEmptyRetry)
                .compose(this.bindToLifecycleDestroy())
                .compose(new DebounceObservableTransformer<Object>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        binding.statusLayout.showLoadingView();
                    }
                });
        // 过滤操作
        RxView.clicks(binding.category)
                .compose(new DebounceObservableTransformer<>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        showCategoryList();
                    }
                });
        RxView.clicks(binding.integral)
                .compose(new DebounceObservableTransformer<>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        showIntegralList();
                    }
                });
        RxView.clicks(binding.selectionBackground)
                .compose(new DebounceObservableTransformer<>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        dimissCategoryList();
                        dimissIntegralList();
                    }
                });
        // 商品列表内容
        RxView.clicks(binding.llErrorServerContent.btErrorServerRetry)
                .compose(this.bindToLifecycleDestroy())
                .compose(new DebounceObservableTransformer<Object>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        binding.statusLayoutGoods.showLoadingView();
                    }
                });
        RxView.clicks(binding.llErrorNetContent.btErrorNetRetry)
                .compose(this.bindToLifecycleDestroy())
                .compose(new DebounceObservableTransformer<Object>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        binding.statusLayoutGoods.showLoadingView();
                    }
                });
        RxView.clicks(binding.llEmptyContent.btEmptyRetry)
                .compose(this.bindToLifecycleDestroy())
                .compose(new DebounceObservableTransformer<Object>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        binding.statusLayoutGoods.showLoadingView();
                    }
                });

        binding.statusLayout.setOnLoadingListener(new StatusLayout.OnLoadingListener() {
            @Override
            public void onLoading() {
                presenter.refreshInit(userInfo, categoryBean);
            }
        });
        binding.statusLayoutGoods.setOnLoadingListener(new StatusLayout.OnLoadingListener() {
            @Override
            public void onLoading() {
                // todo : 首次刷新商品列表
                presenter.refreshGoodsInit(userInfo, selectedCategoryModel, selectedTagModel, selectIntegralModel);
            }
        });
        binding.refreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                presenter.refreshGoods(userInfo, selectedCategoryModel, selectedTagModel, selectIntegralModel);
            }

            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                presenter.loadmoreGoods(userInfo, selectedCategoryModel, selectedTagModel, selectIntegralModel);
            }

        });
    }

    private void initData(Bundle savedInstanceState) {
        presenter.bind(this);
    }

    @Override
    public void onUser(User user) {
        userInfo = user;
        binding.statusLayout.showLoadingView();
    }

    @Override
    public void refreshInitServerFailed(String msg) {
        binding.statusLayout.showErrorServerView();
        ToastManager.show(this, msg);
    }

    @Override
    public void refreshInitNetFailed(String message) {
        binding.statusLayout.showErrorServerView();
        ToastManager.show(this, message);
    }

    @Override
    public void onGoodsItemClicked(JDGoodsItemBean item) {
        Logger.d("onGoodsItemClicked : \n " + GsonUtils.toJsonString(item, true));
        JDGoodsDetailActivity.startActivity(this, item);
    }

    @Override
    public void onItemClicked(JDCategorySelectModel item) {
        dimissCategoryList();
        if (selectedCategoryModel.equals(item)) {
            return;
        }
        selectedCategoryModel = item;
        /**
         * 刷新二级tag数据
         */
        Single.just(item.getGoodsCategoryBean().getNodes())
                .map(new Function<List<JDGoodsCategoryBean>, List<JDCategoryTagModel>>() {
                    @Override
                    public List<JDCategoryTagModel> apply(List<JDGoodsCategoryBean> jdGoodsCategoryBeans) throws Exception {
                        List<JDCategoryTagModel> categoryTagModels = new ArrayList<>();
                        for (JDGoodsCategoryBean goodsCategoryBean : jdGoodsCategoryBeans) {
                            JDCategoryTagModel categoryTagModel = new JDCategoryTagModel();
                            categoryTagModel.setGoodsCategoryBean(goodsCategoryBean);
                            categoryTagModels.add(categoryTagModel);
                        }
                        return categoryTagModels;
                    }
                })
                .doOnSuccess(new Consumer<List<JDCategoryTagModel>>() {
                    @Override
                    public void accept(List<JDCategoryTagModel> jdCategoryTagModels) throws Exception {
                        if (jdCategoryTagModels.size() > 0) {
                            jdCategoryTagModels.get(0).setSelected(true);
                        }
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<List<JDCategoryTagModel>>() {
                    @Override
                    public void accept(List<JDCategoryTagModel> jdCategoryTagModels) throws Exception {

                        if (jdCategoryTagModels.size() > 0) {
                            selectedTagModel = jdCategoryTagModels.get(0);
                        } else {
                            selectedTagModel = null;
                        }

                        // todo : 更新二级类别
                        categoryTagsAdapter.setItems(jdCategoryTagModels);
                        categoryTagsAdapter.notifyDataSetChanged();

                        /**
                         * todo : 更新一级类别
                         */
                        binding.categoryTitle.setText(item.getGoodsCategoryBean().getClassName());
                        dimissCategoryList();
                        if (goodsAdapter.getItems().size() <= 0) {
                            /**
                             * 空界面，重新刷新
                             */
                            binding.statusLayoutGoods.showLoadingView();
                        } else {
                            /**
                             * 下拉刷新
                             */
                            binding.refreshLayout.autoRefresh();
                        }
                    }
                });
    }

    @Override
    public void onItemClicked(JDIntegralSelectModel item) {
        dimissIntegralList();
        if (selectIntegralModel.equals(item)) {
            return;
        }
        selectIntegralModel = item;
        binding.integralTitle.setText(item.getScopeType().getDesc());
        if (goodsAdapter.getItems().size() <= 0) {
            binding.statusLayoutGoods.showLoadingView();
        } else {
            binding.refreshLayout.autoRefresh();
        }
    }

    @Override
    public void onTagClicked(JDCategoryTagModel item) {
        if (selectedTagModel.equals(item)) {
            return;
        }
        selectedTagModel = item;
        if (goodsAdapter.getItems().size() <= 0) {
            binding.statusLayoutGoods.showLoadingView();
        } else {
            binding.refreshLayout.autoRefresh();
        }
    }

    /**
     * todo : 更新category filter , tag filter, integral filter
     * @param data3ResultSet
     */
    @Override
    public void updateCategoryTagListViews(Data3ResultSet<List<JDCategorySelectModel>, List<JDCategoryTagModel>, List<JDIntegralSelectModel>> data3ResultSet) {

        List<JDCategorySelectModel> categorySelectModels = data3ResultSet.data1;
        List<JDCategoryTagModel> categoryTagModels = data3ResultSet.data2;
        List<JDIntegralSelectModel> integralSelectModels = data3ResultSet.data3;

        selectedCategoryModel = categorySelectModels.get(0);
        if (categoryTagModels != null && categoryTagModels.size() > 0) {
            selectedTagModel = categoryTagModels.get(0);
        }
        selectIntegralModel = integralSelectModels.get(0);

        categoryListAdapter.setItems(categorySelectModels);
        if (categoryTagModels == null) {
            categoryTagModels = new ArrayList<>();
        }
        categoryTagsAdapter.setItems(categoryTagModels);
        integralListAdapter.setItems(integralSelectModels);

        categoryListAdapter.notifyDataSetChanged();
        categoryTagsAdapter.notifyDataSetChanged();
        integralListAdapter.notifyDataSetChanged();

        dimissCategoryList();
        dimissIntegralList();

        binding.categoryTitle.setText(selectedCategoryModel.getGoodsCategoryBean().getClassName());
        binding.integralTitle.setText(selectIntegralModel.getScopeType().getDesc());

        // todo
        binding.statusLayout.post(new Runnable() {
            @Override
            public void run() {
                /**
                 * 显示整体内容布局
                 */
                binding.statusLayout.showContentView();
                /**
                 * 获取产品列表
                 */
                binding.statusLayoutGoods.showLoadingView();
            }
        });
    }

    @Override
    public void refreshGoodsInitSuccess(JDGoodsListResultBean jdGoodsListResultBean) {
        List<JDGoodsItemBean> datas = jdGoodsListResultBean.getDatas();
        Single.just(datas)
//                .map(new Function<List<JDGoodsItemBean>, List<JDGoodsItemModel>>() {
//                    @Override
//                    public List<JDGoodsItemModel> apply(List<JDGoodsItemBean> jdGoodsItemBeans) throws Exception {
//                        List<JDGoodsItemModel> datas = new ArrayList<>();
//                        for (int i = 0; i < jdGoodsItemBeans.size(); i++) {
//                            JDGoodsItemModel jdGoodsItemModel = new JDGoodsItemModel();
//                            jdGoodsItemModel.setGoodsItemBean(jdGoodsItemBeans.get(i));
//                            jdGoodsItemModel.setShowLeftDivider((i + 1) % 2 == 0);
//                            datas.add(jdGoodsItemModel);
//                        }
//                        return datas;
//                    }
//                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SingleObserver<List<JDGoodsItemBean>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onSuccess(List<JDGoodsItemBean> jdGoodsItemBeans) {
                        if (jdGoodsItemBeans.size() <= 0) {
                            binding.statusLayoutGoods.showEmptyView();
                            goodsAdapter.setItems(jdGoodsItemBeans);
                            goodsAdapter.notifyDataSetChanged();
                        } else {
                            binding.statusLayoutGoods.showContentView();
                            goodsAdapter.setItems(jdGoodsItemBeans);
                            goodsAdapter.notifyDataSetChanged();
                            binding.refreshLayout.setEnableLoadmore(jdGoodsItemBeans.size() >= PageInfo.SIZE_DEFAULT);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        binding.statusLayoutGoods.showErrorServerView();
                    }
                });
    }

    @Override
    public void refreshGoodsInitServerFailed(String msg) {
        binding.statusLayoutGoods.showErrorServerView();
    }

    @Override
    public void refreshGoodsInitNetFailed(String message) {
        binding.statusLayoutGoods.showErrorNetworkView();
    }

    @Override
    public void refreshGoodsSuccess(JDGoodsListResultBean jdGoodsListResultBean) {
        binding.refreshLayout.finishRefresh(true);
        if (jdGoodsListResultBean.getDatas().size() <= 0) {
            binding.statusLayoutGoods.showEmptyView();
            goodsAdapter.setItems(jdGoodsListResultBean.getDatas());
            goodsAdapter.notifyDataSetChanged();
        } else {
            binding.statusLayoutGoods.showContentView();
            goodsAdapter.setItems(jdGoodsListResultBean.getDatas());
            goodsAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void refreshGoodsServerFailed(String msg) {
        binding.refreshLayout.finishRefresh(false);
        ToastManager.show(this, msg);
    }

    @Override
    public void refreshGoodsNetFailed(String message) {
        binding.refreshLayout.finishRefresh(false);
        ToastManager.show(this, message);
    }

    @Override
    public void loadmoreGoodsSuccess(JDGoodsListResultBean jdGoodsListResultBean) {
        binding.refreshLayout.finishLoadmore(true);
        binding.refreshLayout.setEnableLoadmore(jdGoodsListResultBean.getDatas().size() >= PageInfo.SIZE_DEFAULT);
        List<Object> items = (List<Object>) goodsAdapter.getItems();
        int startPosition = items.size();
        items.addAll(jdGoodsListResultBean.getDatas());
        goodsAdapter.notifyItemRangeInserted(startPosition, jdGoodsListResultBean.getDatas().size());
    }

    @Override
    public void loadmoreGoodsServerFailed(String msg) {
        binding.refreshLayout.finishLoadmore(false);
        ToastManager.show(this, msg);
    }

    @Override
    public void loadmoreGoodsNetFailed(String message) {
        binding.refreshLayout.finishLoadmore(false);
        ToastManager.show(this, message);
    }

    /**
     * 显示类别选择列表
     */
    public void showCategoryList() {
        binding.selectionBackground.setVisibility(View.VISIBLE);
        binding.integralList.setVisibility(View.GONE);
        binding.categoryList.setVisibility(View.VISIBLE);
    }

    public void dimissCategoryList() {
        binding.selectionBackground.setVisibility(View.GONE);
        binding.categoryList.setVisibility(View.GONE);
        binding.integralList.setVisibility(View.GONE);
    }

    /**
     * 显示积分范围选择列表
     */
    public void showIntegralList() {
        binding.selectionBackground.setVisibility(View.VISIBLE);
        binding.categoryList.setVisibility(View.GONE);
        binding.integralList.setVisibility(View.VISIBLE);
    }

    public void dimissIntegralList() {
        binding.selectionBackground.setVisibility(View.GONE);
        binding.integralList.setVisibility(View.GONE);
        binding.categoryList.setVisibility(View.GONE);
    }

    @Override
    public void onLoading() {

    }

    @Override
    public void onLoaded() {

    }

    @Override
    public void onBackPressed() {
        if (binding.selectionBackground.isShown()) {
            dimissIntegralList();
            dimissCategoryList();
            return;
        }
        super.onBackPressed();
    }

    @Override
    public double getExchangeRate() {
        return exchangeRate;
    }
}
